<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <title>写博客</title>
    <base href="<%=request.getContextPath()%>/">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="static/layui/css/layui.css">
    <script src="static/jquery/jquery.js"></script>
    <script src="static/jquery/js.cookie.js"></script>
    <script src="static/layui/layui.js"></script>
    <script src="static/layui/xm-select.js"></script>
    <script src="static/front/js/banner.js"></script>
    <link rel="icon" href="static/images/favicon.ico">
    <style>
        .main {
            height: 100vh;
            width: 100vw;
            overflow: hidden;
            display: flex;
        }

        .main .anthology {
            width: 15%;
            overflow-y: scroll;
            background-color: #2a2a2a;
        }

        .main .anthology .home {
            height: 10%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .main .anthology .home .btn {
            height: 48px;
            width: 80%;
            border-radius: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid palevioletred;
        }

        .main .anthology .home .btn a {
            display: flex;
            align-items: center;
            justify-content: center;
            color: palevioletred;
            height: 100%;
            width: 100%;

        }

        .main .anthology .anthology-group {
            height: 90%;
            width: 90%;
            margin: 0 auto;
        }

        .main .anthology .anthology-group .anthology-opt {
        }

        .main .anthology .anthology-group .anthology-opt > a {
            display: flex;
            align-items: center;
            height: 40px;
            width: 100%;
            color: white;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form {
            height: 80px;
            padding: 10px 0;
            display: none;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-input {
            height: 40px;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-input input {
            display: block;
            height: 30px;
            padding-left: 8px;
            background-color: #6e7681;
            color: white;
            border: 1px solid #5f5f5f;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-input input::placeholder {
            color: #5f5f5f;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn {
            height: 30px;
            display: flex;
            align-items: center;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn > div {
            height: 26px;
            width: 60px;
            margin-right: 15px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn .submit-btn {
            border: 1px solid green;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn .submit-btn a {
            color: green;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn .cancel-btn {
            border: 1px solid orange;
        }

        .main .anthology .anthology-group .anthology-opt .anthology-form .anthology-btn .cancel-btn a {
            color: orange;
        }

        .main .anthology .anthology-group .anthology-list {

        }

        .main .anthology .anthology-group .anthology-list li {
            height: 40px;
            display: flex;
            align-items: center;
            cursor: pointer;
            padding-left: 10px;
        }

        .main .anthology .anthology-group .anthology-list li a {
            color: white;
            display: flex;
            height: 100%;
            width: 90%;
            align-items: center;
        }

        .main .anthology .anthology-group .anthology-list li i {
            color: white;
            display: none;
            align-items: center;
        }

        .main .anthology .anthology-group .anthology-list li i.anthology-icon-active {
            display: flex;
        }

        .main .anthology .anthology-group .anthology-list li:hover {
            background-color: rgba(255, 255, 255, .3);
        }

        .main .anthology .anthology-group .anthology-list li.anthology-active {
            background-color: rgba(255, 255, 255, .3);
            border-left: 2px solid palevioletred;
        }

        .main .list {
            width: 20%;
            height: 100%;
            background-color: #999999;
            overflow-y: scroll;
        }

        .main .list .create-btn {
            height: 10%;
            border-bottom: 1px solid #cccccc;
            padding-left: 20px;
        }

        .main .list .create-btn a {
            display: flex;
            height: 100%;
            align-items: center;
            font-size: 20px;
        }

        .main .list .create-btn a i {
            margin-right: 5px;
        }

        .main .list .article-list {

        }

        .main .list .article-list li {
            height: 40px;
            display: flex;
            align-items: center;
            cursor: pointer;
            padding-left: 10px;
        }

        .main .list .article-list li a {
            color: white;
            display: flex;
            height: 100%;
            width: 70%;
            align-items: center;
        }

        .main .list .article-list li i {
            color: white;
            display: none;
            align-items: center;
        }

        .main .list .article-list li i.article-icon-active {
            display: flex;
        }

        .main .list .article-list li:hover {
            background-color: rgba(255, 255, 255, .3);
        }

        .main .list .article-list li.article-active {
            background-color: rgba(255, 255, 255, .3);
            border-left: 2px solid palevioletred;
        }

        .main .edit {
            width: 65%;
            height: 100%;
            background-color: #fff;
            overflow-y: scroll;
        }

        .main .edit .form-group {
            width: 90%;
            margin: 10px auto;
            display: none;
        }

        .main .edit .form-group .word-limit {
            position: absolute;
            right: 5px;
            bottom: 5px;
        }
    </style>
    <style>
        .upload-group .upload-btn {
            height: 50px;
        }

        .upload-group .image-group {
            display: flex;
            flex-wrap: wrap;
        }

        .upload-group .image-group .image-item {
            height: 110px;
            width: 110px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .upload-group .image-group .image-item:hover .img-opt {
            display: flex;
        }

        .upload-group .image-group .image-item .img-view {
            height: 100px;
            width: 100px;
            outline: 1px solid #333;
        }

        .upload-group .image-group .image-item .img-view img {
            display: block;
            height: 100%;
            width: 100%;
        }

        .upload-group .image-group .image-item .img-opt {
            height: 100%;
            width: 100%;
            position: absolute;
            background-color: rgba(255, 255, 255, .5);
            display: none;
            align-items: center;
            justify-content: center;
        }


        .upload-group .image-group .image-item .img-opt i {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 40px;
            width: 40px;
            font-size: 20px;
            cursor: pointer;
        }

    </style>
</head>
<body>
<div class="main">
    <div class="anthology">
        <div class="home">
            <div class="btn">
                <a href="page/index">回到首页</a>
            </div>
        </div>
        <div class="anthology-group">
            <div class="anthology-opt">
                <a href="javascript:;" id="createAnthologyBtn">
                    <i class="layui-icon layui-icon-addition"></i>
                    新建文集
                </a>
                <div class="anthology-form">
                    <div class="anthology-input">
                        <input type="hidden" id="anthologyId">
                        <input type="text" id="anthologyName" placeholder="请输入文集名称">
                    </div>
                    <div class="anthology-btn">
                        <div class="submit-btn"><a href="javascript:;" id="saveFormBtn">保存</a></div>
                        <div class="cancel-btn"><a href="javascript:;" id="cancelFormBtn">取消</a></div>
                    </div>
                </div>
            </div>
            <div class="anthology-list">
                <ul id="anthology">


                </ul>
            </div>
        </div>
    </div>
    <div class="list">
        <div class="create-btn">
            <a href="javascript:;" id="createArticleBtn"><i class="layui-icon layui-icon-add-circle"></i>新建博客</a>
        </div>
        <div class="article-list">
            <ul id="article">

            </ul>
        </div>
    </div>
    <div class="edit">
        <div class="form-group">
            <el-form class="layui-form">
                <input type="hidden" name="articleId" id="articleId">
                <div class="layui-form-item">
                    <label for="title" class="layui-form-label"><span style="color: red">*</span>标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" id="title" placeholder="博客标题" class="layui-input"
                               lay-verify="required" lay-reqtext="请填写博客标题">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="profile" class="layui-form-label">摘要</label>
                    <div class="layui-input-block">
                        <textarea name="profile" style="resize: none;" id="profile" class="layui-textarea"
                                  placeholder="博客摘要"
                                  maxlength="150"></textarea>
                        <span class="word-limit" id="wordLimit">0/150</span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label for="categoryId" class="layui-form-label">文章分类</label>
                        <div class="layui-input-inline">
                            <select name="categoryId" id="categoryId">
                                <option value="1">武侠</option>
                                <option value="2">随笔</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label for="commentStatus" class="layui-form-label">评论选项</label>
                        <div class="layui-input-inline">
                            <select name="commentStatus" id="commentStatus">
                                <option value="1">允许评论</option>
                                <option value="2">禁止评论</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="tagIds" class="layui-form-label">文章标签</label>
                    <div class="layui-input-block">
                        <div id="tagIds"></div>
                    </div>
                </div>
                <div class="layui-form-item ">
                    <label for="coverBtn" class="layui-form-label">封面</label>
                    <input type="hidden" id="cover" name="cover">
                    <div class="layui-input-block">
                        <div class="upload-group">
                            <div class="upload-btn">
                                <button type="button" class="layui-btn" id="coverBtn">上传封面</button>
                            </div>
                            <div class="image-group" id="coverImage">

                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="content" class="layui-form-label">正文</label>
                    <div class="layui-input-block">
                        <div id="content"></div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label></label>
                    <div class="layui-input-block">
                        <button lay-submit class="layui-btn" lay-filter="apply">直接发布</button>
                        <button lay-submit class="layui-btn layui-bg-orange" lay-filter="save">保存草稿</button>
                    </div>
                </div>
            </el-form>
        </div>
    </div>
</div>
</body>
<script src="static/common/js/ajax.js"></script>
<script src="static/common/js/base.js"></script>
<script>
    let anthologyList = [];/*初始化文集列表*/
    let dropdown;
    let form;
    let tagSelect;
    let tinEdit;
    let tm;
    $(function () {
        if (!getLoginInfo()) {
            layer.alert('请先登录！', {icon: 5}, function () {
                location.href = "blog/index";
            })
        }
        /*新建文集按钮*/
        $("#createAnthologyBtn").click(function () {
            $(".anthology-form").slideDown(800);
            $("#saveFormBtn").text("保存");
        });
        /*保存文集按钮*/
        $("#saveFormBtn").click(function () {
            const name = $("#anthologyName").val();
            if (!name) {
                layer.alert("请输入文集名称！", {icon: 5});
                return false;
            }
            http.post("article/anthology/update", {name, anthologyId: $("#anthologyId").val()}, function () {
                layer.msg("添加成功！", {icon: 6});
                $("#anthologyName").val("");
                $("#anthologyId").val("");
                $(".anthology-form").slideUp(800);
                sessionStorage.removeItem("anthologyId")
                getAnthologyList();
            })
        });
        /*取消新建文集按钮*/
        $("#cancelFormBtn").click(function () {
            $("#anthologyName").val("");
            $("#anthologyId").val("");
            $(".anthology-form").slideUp(800);
        });
        /*配置多行文本框计数器*/
        $("#profile").on("input", function () {
            const maxLength = $(this).prop("maxlength");
            const len = this.value.length;
            $("#wordLimit").text(len + "/" + maxLength);
            if (len >= maxLength) {
                $("#wordLimit").css("color", "red");
            } else {
                $("#wordLimit").css("color", "black");
            }
        });
        /*新建博客按钮*/
        $("#createArticleBtn").click(function () {
            const d = new Date();
            let year = d.getFullYear();
            let month = d.getMonth();
            let date = d.getDate();
            const title = year + "-" + (month < 10 ? "0" + month : month) + "-" + (date < 10 ? "0" + date : date);

            http.post('article/update', {
                title,
                articleStatus: 2,
                anthologyId: sessionStorage.getItem("anthologyId")
            }, function () {
                sessionStorage.removeItem("articleId");
                getArticleList();
            })
        });

    })

    layui.extend({
        tinymce: 'static/layui/tinymce/tinymce'/*加载tinymce富文本编辑器*/
    }).use(['dropdown', 'upload', 'tinymce', 'form'], function () {
        dropdown = layui.dropdown;
        form = layui.form;
        const upload = layui.upload;
        tm = layui.tinymce;
        getAnthologyList();//加载文集

        /*监听表单提交*/
        form.on("submit(apply)", function (data) {
            submitBlog(data, 1);
            return false;
        });
        form.on("submit(save)", function (data) {
            submitBlog(data, 2);
            return false;
        });
        /*渲染上传按钮*/
        upload.render({
            elem: "#coverBtn",
            url: "upload",
            data: {type: "cover"},
            acceptMime: 'image/*',
            size: 1024 * 1024 * 20,/*单位kb*/
            done(res) {
                if (res.code === 200) {
                    setCover(res.msg);
                }
            },
            error(e) {
                console.log(e);
                layer.msg('封面上传异常！', {icon: 2});
            }
        });
    });

    /*设置封面图片*/
    function setCover(fileName) {
        $("#cover").val(fileName);
        if (fileName) {
            let $html = '<div class="image-item"><div class="img-view"><img src="static/upload/' + fileName + '" alt="' + fileName + '"></div><div class="img-opt"><i onclick="showImage(this)" title="查看原图" class="layui-icon layui-icon-search"></i><i onclick="delCover()" title="删除图片" class="layui-icon layui-icon-delete"></i></div></div>';
            $("#coverImage").empty().append($html);
        } else {
            $("#coverImage").empty();
        }
    }

    /*删除封面图片*/
    function delCover() {
        layer.confirm('确定删除该图片吗?', {icon: 3, title: "询问"}, function (index) {
            setCover();
            layer.close(index);
        })
    }

    /*预览封面图片*/
    function showImage(_this) {
        const fileName = $(_this).parents(".image-item").find('img').prop('alt')
        layer.photos({
            photos: {
                data: [{
                    alt: fileName,
                    src: 'static/upload/' + fileName
                }]
            }
        })
    }

    function getAnthologyList() {
        http.get("article/anthology/list", null, function (res) {
            if (res.data.length > 0) {
                let $html = '';
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].status === 1) {
                        /*处理文集数组用于文章转移文集的列表*/
                        anthologyList.push({id: res.data[i].anthologyId, title: res.data[i].name})
                        $html += '<li data-id="' + res.data[i].anthologyId + '"><a href="javascript:;" class="anthology-name">' + res.data[i].name + '</a><i class="layui-icon layui-icon-set-sm anthology-icon" data-id="' + res.data[i].anthologyId + '" data-name="' + res.data[i].name + '"></i></li>';
                    }
                }
                /*文集列表插入到页面中*/
                $("#anthology").empty().append($html);
                let liIndex = 0;
                let anthologyId = sessionStorage.getItem("anthologyId");
                if (anthologyId) {
                    $("#anthology li").each((index, item) => {
                        if ($(item).data("id") == anthologyId) {
                            liIndex = index;
                        }
                    })
                }
                /*初始化文集列表样式*/
                $("#anthology li:eq(" + liIndex + ")").addClass("anthology-active");
                $("#anthology li i:eq(" + liIndex + ")").addClass("anthology-icon-active");
                /*获取默认文集的文章*/
                sessionStorage.setItem("anthologyId", $("#anthology li:eq(" + liIndex + ")").data("id"));
                getArticleList();
                /*文集列表样式控制*/
                $(".anthology-list li").click(function () {
                    /*设置切换样式*/
                    $(this).addClass("anthology-active").siblings("li").removeClass("anthology-active");
                    $(".anthology-list i").removeClass("anthology-icon-active");
                    $(this).find("i").addClass("anthology-icon-active");
                    sessionStorage.setItem("anthologyId", $(this).data("id"));
                    /*加载数据*/
                    getArticleList();
                })
                /*渲染文集操作按钮*/
                dropdown.render({
                    elem: ".anthology-icon",
                    data: [{
                        title: "修改",
                        id: "edit"
                    }, {
                        title: "删除",
                        id: "delete"
                    }],
                    click(data) {
                        const anthologyId = $(this.elem).data("id");
                        const anthologyName = $(this.elem).data("name");
                        if (data.id === "edit") {
                            $(".anthology-form").slideDown(800);
                            $("#anthologyName").val(anthologyName);
                            $("#anthologyId").val(anthologyId);
                            $("#saveFormBtn").text("修改");
                        } else {
                            layer.confirm('确定删除该文集吗?', {icon: 3, title: "询问"}, function (index) {
                                http.delete("article/anthology/delete/" + anthologyId, null, function () {
                                    layer.msg("删除文集成功", {icon: 6})
                                    getAnthologyList()
                                })
                                layer.close(index);
                            })
                        }
                    }
                })
            } else {
                $("#anthology").empty();
            }
        })
    }

    function getArticleList() {
        http.get("article/list/" + sessionStorage.getItem("anthologyId"), null, function (res) {
            if (res.data.length > 0) {
                /*渲染博客列表*/
                let $html = '';
                for (let article of res.data) {
                    let $span = '<span class="layui-bg-green" style="padding: 0 5px;margin-right:5px">发布</span>';
                    if (article.articleStatus === 2) {
                        $span = '<span class="layui-bg-orange" style="padding: 0 5px;margin-right:5px">草稿</span>';
                    }
                    /*使用js方式分割字符串，让内容较长的自动截取*/
                    let title = article.title;
                    if (title.length > 16) {
                        title = title.substring(0, 16) + '...';
                    }
                    $html += '<li data-id="' + article.articleId + '"><a title="' + article.title + '" href="javascript:;">' + title + '</a>' + $span + '<i class="layui-icon layui-icon-set-fill article-icon" data-id="' + article.articleId + '"></i></li>';
                }
                /*文集列表插入到页面中*/
                $("#article").empty().append($html);
                let articleId = sessionStorage.getItem("articleId");
                let liIndex = 0;
                if (articleId) {
                    $("#article li").each((index, item) => {
                        if ($(item).data("id") == articleId) {
                            liIndex = index;
                        }
                    })
                }
                /*初始化文集列表样式*/
                $("#article li:eq(" + liIndex + ")").addClass("article-active");
                $("#article li i:eq(" + liIndex + ")").addClass("article-icon-active");
                /*文章列表样式控制*/
                $(".article-list li").click(function () {
                    $(this).addClass("article-active").siblings("li").removeClass("article-active");
                    $(".article-list i").removeClass("article-icon-active");
                    $(this).find("i").addClass("article-icon-active");
                    getTagList();
                    getCategoryList();
                    sessionStorage.setItem("articleId", $(this).data("id"))
                    getArticleById();
                })
                /*处理下拉菜单的子级选项*/
                let child = anthologyList.filter(item => item.id != sessionStorage.getItem("anthologyId"));
                /*渲染文章操作按钮*/
                dropdown.render({
                    elem: ".article-icon",
                    data: [{
                        title: "移动",
                        id: "move",
                        parent: true,
                        child
                    }, {
                        title: "删除",
                        id: "delete",
                        parent: true
                    }],
                    click(data) {
                        if (data.parent) {
                            const articleId = $(this.elem).data("id")
                            layer.confirm('确定删除该博客吗?', {icon: 3, title: "询问"}, function (index) {
                                http.delete("article/delete/" + articleId, null, function () {
                                    layer.msg('删除成功！', {icon: 6});
                                    getArticleList();
                                })
                                layer.close(index);
                            })
                        } else {
                            http.post("article/update", {
                                articleId: $(this.elem).data("id"),
                                anthologyId: data.id
                            }, function () {
                                getArticleList();
                            })
                        }
                    }
                })
                /*显示博客编辑页面*/
                $(".form-group").show();
                /*获取标签列表*/
                getTagList();
                /*获取分类列表*/
                getCategoryList();
                sessionStorage.setItem("articleId", $("#article li:eq(" + liIndex + ")").data("id"))
                /*获取文章信息*/
                getArticleById();
            } else {
                $(".form-group").hide();
                $("#article").empty()
            }
        })
    }

    function getTagList() {
        http.get("article/tag/list", null, function (res) {
            const xmList = res.data.map(item => {
                return {
                    name: item.name,
                    value: item.tagId,
                    disabled: item.status === 2
                }
            })
            tagSelect = xmSelect.render({
                el: "#tagIds",
                filterable: true,
                data: xmList,
                name: "tagIds",
                tips: "请选择博客标签",
                searchTips: '不存在则会自动创建',
                max: 5,
                toolbar: {
                    show: true
                },
                create: function (val, arr) {
                    let go = true;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].name === val) {
                            go = false;
                        }
                    }
                    if (go) {
                        let tagObj = {name: val, value: val, type: "new"};
                        return tagObj;
                    }

                },
                autoRow: true,
                height: "200px"
            })
        })
    }

    function getCategoryList() {
        http.get("blog/category/list", null, function (res) {
            let $html = '';
            for (const category of res.data) {
                let disabled = 'disabled';
                if (category.status === 1) {
                    disabled = "";
                }
                $html += '<option ' + disabled + ' value="' + category.categoryId + '">' + category.name + '</option>';
            }
            $("#categoryId").empty().append($html);
            /*动态追加下拉框之后，要重新渲染form*/
            form.render();
        })
    }

    function getArticleById() {
        http.get("article/info/" + sessionStorage.getItem("articleId"), null, function (res) {
            const article = res.data;
            $("#articleId").val(article.articleId);
            $("#title").val(article.title);
            $("#profile").val(article.profile);
            $("#categoryId").val(article.categoryId);
            $("#commentStatus").val(article.commentStatus);
            setCover(article.cover);
            /*处理多选标签的数组*/
            const tagIds = article.articleTagList.map(item => item.tagId)
            tagSelect.setValue(tagIds);
            /*动态追加下拉框之后，要重新渲染form*/
            form.render();
            /*渲染tinymce富文本编辑器*/
            tm.render({
                elem: "#content",
                images_upload_url: "upload",
                images_upload_base_path: 'static/upload/',
                autosave_prefix: "jf_blog_",
                form: {
                    name: "file",
                    data: {type: "edit"}
                },
                height: 500,
            }, (opt, edit) => {
                tinEdit = edit;
                /*设置富文本编辑框的内容*/
                tinEdit.resetContent();
                if (article.content) {
                    tinEdit.setContent(article.content);
                } else {
                    tinEdit.setContent("");
                }

            });
            tinEdit = tm.get("#content");
        })
    }

    function submitBlog(data, articleStatus) {
        /*获取标签选项的选中列表*/
        const tags = tagSelect.getValue();
        const tagIds = [];
        const newTags = [];
        for (const t of tags) {
            if (t.type) {
                newTags.push(t.name)
            } else {
                tagIds.push(t.value)
            }
        }
        const content = tinEdit.getContent();
        if (articleStatus === 1) {
            if (!data.field.categoryId) {
                layer.msg("请选择博客分类！", {icon: 5});
                return false;
            }
            if (!content) {
                layer.msg("请输入博客正文内容！", {icon: 5});
                return false;
            }
        }
        const anthologyId = sessionStorage.getItem("anthologyId");
        data.field.content = content
        data.field.anthologyId = anthologyId
        data.field.articleStatus = articleStatus;
        data.field.tagIds = tagIds;
        data.field.newTags = newTags;

        http.post("article/update", data.field, function () {
            layer.msg("操作成功！", {icon: 6});
            localStorage.removeItem("jf_blog_draft")
            localStorage.removeItem("jf_blog_time")
            tm.reload("#content", {autosave_ask_before_unload: false});
            getArticleList();
        })
    }
</script>
</html>
